package org.abc.fund.service.dataSourceCollection;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class FundDataUpdateScheduler {

    private final FundDataUpdateStrategyService strategyService;
    private final BatchDataCollectionService batchService;

    @Value("${fund.scheduler.enabled:false}")
    private boolean schedulerEnabled;

    @Value("${fund.scheduler.username:}")
    private String schedulerUsername;

    @Value("${fund.scheduler.password:}")
    private String schedulerPassword;

    @Value("${fund.scheduler.fundCodes:}")
    private String schedulerFundCodes;

    private List<String> getFundCodes() {
        if (schedulerFundCodes == null || schedulerFundCodes.isBlank()) {
            return null;
        }
        return List.of(schedulerFundCodes.split(","));
    }

    private boolean ready() {
        if (!schedulerEnabled) {
            return false;
        }
        if (schedulerUsername == null || schedulerUsername.isBlank()
                || schedulerPassword == null || schedulerPassword.isBlank()) {
            log.warn("基金定时任务已启用但未配置账号或密码，已跳过执行");
            return false;
        }
        return true;
    }

    @Scheduled(cron = "${fund.scheduler.daily.cron:0 0 3 * * ?}")
    public void runDailyMarketPlan() {
        executePlan(FundDataUpdateStrategyService.DataUpdatePlan.DAILY_MARKET);
    }

    @Scheduled(cron = "${fund.scheduler.weekly.cron:0 0 4 ? * MON}")
    public void runWeeklyLeveragePlan() {
        executePlan(FundDataUpdateStrategyService.DataUpdatePlan.WEEKLY_LEVERAGE);
    }

    @Scheduled(cron = "${fund.scheduler.monthly.cron:0 30 3 1 * ?}")
    public void runMonthlyFinancialPlan() {
        executePlan(FundDataUpdateStrategyService.DataUpdatePlan.MONTHLY_FINANCIAL);
    }

    private void executePlan(FundDataUpdateStrategyService.DataUpdatePlan plan) {
        if (!ready()) {
            return;
        }
        try {
            BatchDataCollectionService.BatchCollectionConfig config =
                    strategyService.buildConfig(plan, schedulerUsername, schedulerPassword, getFundCodes());
            BatchDataCollectionService.BatchCollectionResult result =
                    batchService.executeBatchCollection(config);
            log.info("计划 {} 执行完成：成功处理 {} 支基金，失败 {} 支",
                    plan.name(), result.getSuccessCount(), result.getFailureCount());
        } catch (Exception e) {
            log.error("计划 {} 执行失败：{}", plan.name(), e.getMessage(), e);
        }
    }
}











